#include <ftp_user.h>

#include <ftp_util.h>
#include <fmt/format.h>
#include <vector>
#include <sstream>
#include <filesystem>

FTPUser::FTPUser():
	permission_(UserPermission::None),
	username_(""),
	password_(""),
	rootDir_("")
{
}

FTPUser::FTPUser(const std::string& username, const std::string& password, UserPermission permission, const std::string& root) :
	username_(username),
	password_(password),
	rootDir_(std::filesystem::path(root).lexically_normal().string()),
	permission_(permission)
{
}

FTPUser::FTPUser(const std::string& username, const std::string& password, int permission, const std::string& root):
	username_(username),
	password_(password),
	rootDir_(std::filesystem::path(root).lexically_normal().string()),
	permission_(static_cast<UserPermission>(permission))
{
}

FTPUser::FTPUser(const FTPUser& user)
{
	username_ = user.username_;
	password_ = user.password_;
	rootDir_ = user.rootDir_;
	permission_ = user.permission_;
}

void FTPUser::setUsername(const std::string& name)
{
	username_ = name;
}

std::string FTPUser::getUsername()
{
	return username_;
}

void FTPUser::setPassword(const std::string& password)
{
	password_ = password;
}

std::string FTPUser::getPassword()
{
	return password_;
}

void FTPUser::setPermission(UserPermission permission)
{
	permission_ = permission;
}

UserPermission FTPUser::getPermission() const
{
	return permission_;
}

void FTPUser::setRootDir(const std::string& rootDir)
{
	rootDir_ = rootDir;
}

std::string FTPUser::getRootDir() const
{
	return rootDir_;
}

void FTPUser::setCurrentWorkDir(const std::string& workDir)
{
	currentWorkDir_ = std::filesystem::path(fmt::format("{}{}{}", rootDir_, FILE_PATH_SEP, workDir)).lexically_normal().string();
}

std::string FTPUser::getWorkDir() const
{
	std::string workDir = currentWorkDir_.substr(rootDir_.size());
	if (workDir == "") {
		return "/";
	}
	return workDir;
}

bool FTPUser::checkInRootDir(const std::string& filename)
{
	std::string absolutePath = std::filesystem::path(filename).lexically_normal().string();
	if (absolutePath.size() < rootDir_.size())return false;
	for (int i = 0; i < rootDir_.size(); ++i) {
		if (absolutePath[i] != rootDir_[i]) {
			return false;
		}
	}
	return true;
}

std::string FTPUser::getCurrentWorkDir() const
{
	return currentWorkDir_;
}
